package cn.wolfcode.p2p.base.service.impl;

import cn.wolfcode.p2p.base.exception.CustomerException;
import cn.wolfcode.p2p.base.service.ISendVerifyCodeService;
import cn.wolfcode.p2p.base.vo.VerifyCodeVO;
import cn.wolfcode.p2p.util.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Transactional
public class SendVerifyCodeServiceImpl implements ISendVerifyCodeService {
    @Override
    public void sendVerifyCode(String phone) {
        //判断手机号格式是否正确
        AssertUtil.instance()
                .isLength(phone, Constants.LENGTH_PHONE, "无效的手机号")
                .isMobile(phone,"无效的手机号");
        //判断是否频繁发送
        VerifyCodeVO lastVO = UserContext.getVerifyCodeVO();
        Date date = new Date();
        if (lastVO != null) {
            Date lastSendTime = lastVO.getSendTime();
            AssertUtil.instance().isFalse(DateUtil.getSecondsBetween(lastSendTime, date) < Constants.VERIFYCODE_VALID_SECOND,"发送频繁,请稍后再试");
        }
        //创建一个验证码
        String code = UUID.randomUUID().toString().substring(0, Constants.LENGTH_VERIFYCODE);
        //执行发送
        System.out.println("您的验证码为:" + code);
        //send(phone, code);
        //保存发送记录到session中(手机号码,发送时间,验证码)
        VerifyCodeVO vo = new VerifyCodeVO();
        vo.setCode(code);
        vo.setPhone(phone);
        vo.setSendTime(date);
        UserContext.setVerifyCodeVO(vo);
    }

    public void send(String phone, String code){
        Map<String,String> map = new HashMap<>();
        map.put("Uid", "见网络");
        map.put("Key", "见网络");
        map.put("smsMob", phone);
        map.put("smsText", "您的验证码是:" + code +"请在5分钟内使用");
        try {
            String ret = HttpUtil.sendHttpRequest("http://utf8.api.smschinese.cn/", map);
            if(ret.equals("-3")){
                throw new CustomerException("短信发送失败[-3],请联系客服");
            }
        }catch (CustomerException e){
            throw new CustomerException(e.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("系统繁忙中,请稍后再试");
        }
    }
}
